<template>
	<view class="page__content">
		<u-navbar :title="pageConfig.titleName" leftIconColor="#fff" rightIconColor="#fff" :autoBack="true"
			:fixed="false">
		</u-navbar>

		<view class="page__content__main">

			<!-- 判断当前蓝牙适配器是否开启 -->
			<template v-if="pageConfig.showTemplate && 
				(pageConfig.deviceTypeName == 'Bluetooth' || pageConfig.deviceTypeName == 'HID')">
				<!-- 应用内 - 蓝牙连接 -->
				<template v-if="pageConfig.deviceTypeName == 'Bluetooth'">
					<linkBluetooth :choiceDeviceInfo="choiceDeviceInfo"></linkBluetooth>
				</template>

				<!-- 应用外 - 系统蓝牙连接 -->
				<template v-else-if="pageConfig.deviceTypeName == 'HID'">
					<linkHID></linkHID>
				</template>
			</template>

			<!-- 未开启蓝牙适配器，且是蓝牙模块 -->
			<template v-else-if="!pageConfig.showTemplate && 
				(pageConfig.deviceTypeName == 'Bluetooth' || pageConfig.deviceTypeName == 'HID')">
				<!-- 提示开启蓝牙适配器 -->

				<u-empty text="开启蓝牙,以便查找附近蓝牙设备" iconSize="150" icon="/static/tabbar-icons/Bluetooth.png"
					style="height:'35vh'">
					<u-button @click="openBluetoothAdapter" size="small" type="primary" :style="{marginTop:10+'px'} "
						text="立即开启"></u-button>
				</u-empty>
			</template>



			<!-- 应用内 - 串口连接 -->
			<template v-if="pageConfig.deviceTypeName == 'Serial'">
				<linkSerial></linkSerial>
			</template>
		</view>

	</view>
</template>

<script>
	import linkBluetooth from "@/st_qms/components/device_link/link_Bluetooth.vue";
	import linkHID from "@/st_qms/components/device_link/link_HID.vue";
	import linkSerial from "@/st_qms/components/device_link/link_Serial.vue";
	export default {
		components: {
			linkBluetooth,
			linkHID,
			linkSerial
		},
		data() {
			return {
				pageConfig: {
					// 标题名称
					titleName: "",
					// 蓝牙适配器监听器
					bluetoothStateListener: null,
					// 连接模式
					deviceTypeName: "",
					// 是否显示连接 -- 通过条件判断是否显示，默认不显示
					showTemplate: false,
				},
				// 选中的设备信息
				choiceDeviceInfo: {},

			}
		},
		async onLoad() {
			// 获取选中的临时设备数据
			const baseParam = this.$utils.deepClone(this.$store.state.QmsModule.DeviceLinkConfig.tempData_device
				.deviceInfo) || {};
			Object.assign(this.choiceDeviceInfo, baseParam);


			// 蓝牙模式
			if (baseParam.Communication == "Bluetooth" || baseParam.Communication == "HID") {
				// 查询当前蓝牙适配器状态
				const isOn = await this.checkBluetoothStatus();
				console.log(isOn);
				this.pageConfig.showTemplate = isOn;
			} else {
				this.pageConfig.showTemplate = true;
			}

			this.pageConfig.titleName = baseParam?.MeasureName || "设备连接";

			// 设置当前连接模式
			this.pageConfig.deviceTypeName = baseParam.Communication;

			console.log(this.choiceDeviceInfo);



			// 创建分包组件目录，用于区分几块连接功能，避免错乱

		},
		mounted() {
			let that = this;
			// 监听蓝牙适配器状态变化事件
			this.pageConfig.bluetoothStateListener = uni.onBluetoothAdapterStateChange(function(res) {
				that.pageConfig.showTemplate = res.available || false;

			})
		},
		onUnload() {
			// 页面卸载时，移除监听
			if (this.pageConfig.bluetoothStateListener) {
				uni.offBluetoothAdapterStateChange(this.pageConfig.bluetoothStateListener);
				this.pageConfig.bluetoothStateListener = null; // 清空标识
			}
			// 清除选中的设备信息
			this.$store.commit("QmsModule/ChangeAndSetStateData", {
				Name1: 'DeviceLinkConfig.tempData_device',
				data: {
					deviceInfo: {},
					agreement: null,
				},
			});

		},
		methods: {
			openBluetoothAdapter() {

				let sysDeviceInfo = JSON.parse(uni.getStorageSync('sysDeviceInfo'));
				console.log(sysDeviceInfo);
				if (sysDeviceInfo['osName'] == 'ios') {} else if (sysDeviceInfo['osName'] == 'android') {
					// Native.js for Android封装一条通过JS语法直接调用Native Java接口通道，通过plus.android可调用几乎所有的系统API
					const BluetoothAdapter = plus.android.importClass(
						'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
					const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
					console.log(blueadapter);
					if (blueadapter) {
						setTimeout(() => {
							// 判断蓝牙是否开启
							if (blueadapter.isEnabled()) {
								console.log('开启')

							} else {
								// 尝试开启蓝牙（Android原生方法）
								const isOpened = blueadapter.enable(); // 返回boolean，true表示开启成功（部分设备可能需要用户确认）
								console.log('开启结果：', isOpened);
							}
						}, 50)
					}
				}



			},
			// 检查蓝牙是否可用
			checkBluetoothStatus() {
				return new Promise((resolve) => {
					uni.openBluetoothAdapter({
						success() {
							// 蓝牙模块初始化成功，继续获取状态
							uni.getBluetoothAdapterState({
								success(res) {
									console.log('蓝牙状态:', res)
									resolve(res.available) // true = 已开启
								},
								fail() {
									resolve(false)
								}
							})
						},
						fail(err) {
							// 蓝牙模块初始化失败（通常是蓝牙未打开）
							console.log('蓝牙未开启', err)
							resolve(false)
						}
					})
				})
			}

		}
	}
</script>

<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		&__main {}
	}
</style>